//
//  TestLayoutConstraintViewController.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2023/2/21.
//  Copyright © 2023 moon. All rights reserved.
//

#import "TestLayoutConstraintViewController.h"
#import <MKUI/MKUI.h>
#import "TestFunButton.h"

@interface TestItemFunButton : UIView
- (id)initWithTitle:(NSString *)title;
@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) MKUIFlowLayoutConstraint *flowlayout;
@property(nonatomic,assign) BOOL selected;
@property(nonatomic,copy) void(^whenClick)(TestItemFunButton *button);
@end
@implementation TestItemFunButton
- (id)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.font = [UIFont systemFontOfSize:24];
        self.titleLabel.numberOfLines = 2;
        [self addSubview:self.titleLabel];
        self.clipsToBounds = YES;
        self.layer.cornerRadius = 5;
        self.layer.borderColor = [UIColor systemGrayColor].CGColor;
        self.layer.borderWidth = 1;
        self.flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[self.titleLabel] constraintParam:(MKUIFlowLayoutConstraintParam_H_C_C) contentInsets:MKUIEdgeInsetsMakeSameEdge(5) interitemSpacing:5];
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__onTap:)]];
        [self __configUI];
    }
    return self;
}
- (void)__onTap:(id)sender{
    if(self.whenClick){
        self.whenClick(self);
    }
}
- (id)initWithTitle:(NSString *)title{
    if (self=[self init]) {
        self.titleLabel.text = title;
    }
    return self;
}
- (void)setSelected:(BOOL)selected{
    if(_selected!=selected){
        _selected = selected;
        [self __configUI];
    }
}
- (void)__configUI{
    self.titleLabel.textColor = !self.selected?[UIColor systemBlueColor]:[UIColor systemRedColor];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.flowlayout.bounds = bounds;
    [self.flowlayout layoutItemsWithResizeItems:YES];
}
- (CGSize)sizeThatFits:(CGSize)size{
    if(self.titleLabel.text.length==0){
        return CGSizeZero;
    }
    CGSize s = [self.flowlayout sizeThatFits:size resizeItems:YES];
    UIEdgeInsets insets = self.flowlayout.contentInsets;
    CGFloat fontSize = 24;
    CGSize minSize = CGSizeMake(fontSize+insets.left+insets.right, fontSize+insets.top+insets.bottom);
    s.width = MAX(MIN(size.width,s.width),minSize.width);
    s.height = MAX(MIN(size.height,s.height),minSize.height);
    return s;
}
@end

@interface TestItemViewsContainer : UIView
@property(nonatomic,strong) NSMutableArray *itemViews;
@property(nonatomic,strong) MKUIWaterFlowLayoutConstraint *flowlayout;
@property(nonatomic,strong,nullable) TestItemFunButton *selectedItem;
@property(nonatomic,copy) void(^whenSelectItem)(TestItemViewsContainer *container);
@property(nonatomic,copy) void(^whenExpendChange)(TestItemViewsContainer *container);
@property(nonatomic,strong) TestFunButton *expendButton;
@end
@implementation TestItemViewsContainer
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.itemViews = [[NSMutableArray alloc] init];
        self.expendButton = [[TestFunButton alloc] initWithTitle:@"v"];
        [self.expendButton setTitle:@"^" forState:UIControlStateSelected];
        [self.expendButton mk_addClickActionBlock:^(TestItemViewsContainer *self) {
            self.expendButton.selected = !self.expendButton.selected;
            [self __refreshExpendSelected];
            [self __reloadDataWithAnimated:YES];
            if(self.whenExpendChange){
                self.whenExpendChange(self);
            }
        } context:self];
        [self addSubview:self.expendButton];
        
        self.flowlayout = [[MKUIWaterFlowLayoutConstraint alloc] initWithItems:nil constraintParam:(MKUIWaterFlowLayoutConstraintParam_H_C_L) contentInsets:UIEdgeInsetsMake(5, 10, 15, 20) interitemSpacing:10 lineSpacing:20];
        self.flowlayout.lastLineItem = self.expendButton;
        
        self.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.layer.borderWidth = 1;
        
        [self __refreshExpendSelected];
    }
    return self;
}
- (void)__reloadDataWithAnimated:(BOOL)animated{
    [self setNeedsLayout];
}
- (CGSize)sizeThatFits:(CGSize)size{
    UIEdgeInsets insets = UIEdgeInsetsMake(5, 10, 5, 10);
    CGSize s = [self.flowlayout sizeThatFits:size resizeItems:YES];
    s.width += insets.left+insets.right;
    s.height += insets.bottom+insets.top;
    s.width = MIN(size.width,s.width);
    s.height = MIN(size.height,s.height);
    return s;
}
- (void)__refreshExpendSelected{
    if(self.expendButton.selected){
        self.flowlayout.maxLines = NSIntegerMax;
        self.flowlayout.showLastLineItemWithinMaxLine = YES;
//        self.flowlayout.lastLineItem = nil;
    }else{
        self.flowlayout.maxLines = 2;
        self.flowlayout.showLastLineItemWithinMaxLine = NO;
//        self.flowlayout.lastLineItem = self.expendButton;
    }
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.flowlayout.bounds = bounds;
    [self.flowlayout layoutItemsWithResizeItems:YES];
    if(self.flowlayout.maxLines!=0 && self.flowlayout.overMaxLines){
        self.expendButton.hidden = NO;
    }else{
        if(self.flowlayout.itemAttributeSection.itemAttributs.count>2){
            self.expendButton.hidden = NO;
        }else{
            self.expendButton.hidden = YES;
        }
    }
}
- (void)removeAllItems{
    for(UIView *view in self.itemViews){
        [view removeFromSuperview];
    }
    [self.itemViews removeAllObjects];
    self.flowlayout.items = self.itemViews;
    [self setNeedsLayout];
}
- (void)addItemWithTitle:(NSString *)text animated:(BOOL)animated{
    TestItemFunButton *itemView = [[TestItemFunButton alloc] initWithTitle:text];
    @MK_WEAKIFY(self);
    itemView.whenClick = ^(TestItemFunButton *itemView) {
        @MK_NORMALIZE(self);
        if(self.selectedItem==itemView){
            self.selectedItem = nil;
        }else{
            self.selectedItem = itemView;
        }
    };
    [self addSubview:itemView];
    [self.itemViews addObject:itemView];
    self.flowlayout.items = self.itemViews;
    if(animated){
        [UIView animateWithDuration:0.25 animations:^{
            [self setNeedsLayout];
            [self layoutIfNeeded];
        }];
    }else{
        [self setNeedsLayout];
    }
}
- (void)setSelectedItem:(TestItemFunButton *)selectedItem{
    if(selectedItem!=_selectedItem){
        _selectedItem.selected = NO;
        _selectedItem = selectedItem;
        _selectedItem.selected = YES;
        if(self.whenSelectItem){
            self.whenSelectItem(self);
        }
    }
}
- (void)removeItem:(UIView *)itemView animated:(BOOL)animated{
    NSInteger index = [self.itemViews indexOfObject:itemView];
    if(index!=NSNotFound){
        if(self.itemViews.count>1 && index==self.itemViews.count-1){
            index--;
        }
    }
    [itemView removeFromSuperview];
    [self.itemViews removeObject:itemView];
    self.flowlayout.items = self.itemViews;
    if(itemView==self.selectedItem){
        if(index>=0 && index<self.itemViews.count){
            self.selectedItem = self.itemViews[index];
        }else{
            self.selectedItem = nil;
        }
    }
    [self __reloadDataWithAnimated:animated];
}
- (void)updateItem:(TestItemFunButton *)item withTitle:(NSString *)text animated:(BOOL)animated{
    if(!item){
        return;
    }
    item.titleLabel.text = text;
    [self __reloadDataWithAnimated:animated];
}
@end


@interface TestLayoutConstraintViewController ()<UITextFieldDelegate>
@property(nonatomic,strong) UITextField *inputField;
@property(nonatomic,strong) TestFunButton *addButton;
@property(nonatomic,strong) TestFunButton *cleanButton;
@property(nonatomic,strong) TestItemViewsContainer *itemsView;
@end

@implementation TestLayoutConstraintViewController

+ (MKTFuncItem *)funcItem{
    return [MKTFuncItem funcWithName:@"瀑布流布局" viewControllerClass:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.view.backgroundColor = [UIColor mk_colorWithLight:[UIColor whiteColor]];
    self.inputField = [[UITextField alloc] init];
    self.inputField.borderStyle = UITextBorderStyleRoundedRect;
    self.inputField.delegate = self;
    [self.view addSubview:self.inputField];
    //
    self.addButton = [[TestFunButton alloc] initWithTitle:@"添加"];
    [self.addButton mk_addClickActionBlock:^(TestLayoutConstraintViewController *self) {
        [self _addText:self.inputField.text];
    } context:self];
    [self.view addSubview:self.addButton];
    //
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_onViewTap:)]];
    
    //
    self.cleanButton = [[TestFunButton alloc] initWithTitle:@"清除"];
    [self.cleanButton mk_addClickActionBlock:^(TestLayoutConstraintViewController *self) {
        [self _cleanAll];
    } context:self];
    [self.view addSubview:self.cleanButton];
    //
    self.itemsView = [[TestItemViewsContainer alloc] init];
    @MK_WEAKIFY(self);
    self.itemsView.whenSelectItem = ^(TestItemViewsContainer *container) {
        @MK_NORMALIZE(self);
        if(container.selectedItem){
            self.inputField.text = container.selectedItem.titleLabel.text;
            [self.addButton setTitle:@"修改" forState:(UIControlStateNormal)];
        }else{
            self.inputField.text = nil;
            [self.addButton setTitle:@"添加" forState:(UIControlStateNormal)];
        }
    };
    self.itemsView.whenExpendChange = ^(TestItemViewsContainer *container) {
        @MK_NORMALIZE(self);
        [self _onRefresh];
    };
    [self.view addSubview:self.itemsView];
    //
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemRefresh) target:self action:@selector(_onRefresh)];
    //
    [self _addText:@"Test1"];
    [self _addText:@"非常长的文本非常长的文本非常长的文本非常长的文本非常长的文本非常长的文本非常长的文本非常长的文本"];
    [self _addText:@"测试1"];
    [self _addText:@"1"];
    
}
- (void)_onRefresh{
    [self.view setNeedsLayout];
    [self.itemsView setNeedsLayout];
}
- (void)_onViewTap:(id)sender{
    [self.inputField endEditing:YES];
    self.itemsView.selectedItem = nil;
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    CGRect bounds = self.safeBounds;
    UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 10);
    
    
    bounds = UIEdgeInsetsInsetRect(bounds, insets);
    
    MKUIFillingLayoutConstraint *l1 = [[MKUIFillingLayoutConstraint alloc] initWithItems:@[self.inputField,self.addButton,self.cleanButton] fillingItem:self.inputField constraintParam:(MKUIFillingLayoutConstraint_H_C) contentInsets:UIEdgeInsetsZero interitemSpacing:10];
    
    MKUILayoutConstraintItemWrapper *w2 = [MKUILayoutConstraintItemWrapper wrapItem:self.itemsView sizeThatFitsBlock:^CGSize(MKUILayoutConstraintItemWrapper * _Nonnull wrapper, CGSize size, BOOL resizeItems) {
        CGSize s2 = [wrapper.originItem sizeThatFits:size];
        return s2;
    }];
    
    
    MKUIFlowLayoutConstraint *flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[l1,w2] constraintParam:(MKUIFlowLayoutConstraintParam_V_T_L) contentInsets:insets interitemSpacing:10];
    flowlayout.bounds = bounds;
    [flowlayout layoutItemsWithResizeItems:YES];
}
- (void)_cleanAll{
    if(self.itemsView.selectedItem){
        [self.itemsView removeItem:self.itemsView.selectedItem animated:YES];
    }else{
        [self.itemsView removeAllItems];
    }
    [self _onRefresh];
}
- (void)_addText:(NSString *)text{
    if(!text.length){
        return;
    }
    
    if(self.itemsView.selectedItem){
        [self.itemsView updateItem:self.itemsView.selectedItem withTitle:text animated:YES];
    }else{
        [self.itemsView addItemWithTitle:text animated:YES];
    }
    [self _onRefresh];
}

#pragma mark - delegate:UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self _addText:self.inputField.text];
    return YES;
}
@end
